import profile
from django import forms
from django.shortcuts import render_to_response
from django import forms
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.contrib.auth.decorators import login_required
from userprofile.models import userprofile
from social.models import UsageProfile, UsageProfileSettings
from routes.models import Setter
from analytics.views import getHeatmap
from django.http import HttpResponseRedirect
from django.template import RequestContext

GENDER_CHOICES = (
	('', 'Decline'),
	('M', 'Male'),
	('F', 'Female'),
)

def getInitialProfile(user, staff_form):
	dict = {}

	dict["username"] = user.username
	dict["email"] = user.email
	dict["first"] = user.first_name
	dict["last"] = user.last_name

	profile = user.profile

	if not staff_form:
		dict["birthdate"] = profile.birthdate
		dict["gender"] = profile.gender
		#dict["address"] = profile.address
		dict["phone"] = profile.phone
		dict["website"] = profile.website
		dict["about"] = profile.about
	else:
		dict["id_card"] = profile.id_card
		dict["comments"] = profile.comments
		dict["gym_staff"] = False
		if user.profile.gym_staff:
			dict["gym_staff"] = True
		dict["route_setter"] = False
		if len(Setter.objects.filter(user=user)) >= 1:
			dict["route_setter"] = True

	return dict

class StaffForm(forms.Form):
	username = forms.CharField(label=(u'Username'), required=False, max_length=30,
			widget = forms.TextInput(attrs={'readonly':'readonly'}))
	email = forms.EmailField(label=(u'Email Address'), required=True,
			widget = forms.TextInput(attrs={'readonly':'readonly'}))
	first = forms.CharField(label=(u'First Name'), required=True, max_length=30,
			widget = forms.TextInput(attrs={'readonly':'readonly'}))
	last = forms.CharField(label=(u'Last Name'), required=True, max_length=30,
			widget = forms.TextInput(attrs={'readonly':'readonly'}))
	id_card = forms.CharField(label=(u'ID Card Number'), required=False, max_length=50)
	gym_staff = forms.BooleanField(label=(u'Staff Member'), required = False)
	route_setter = forms.BooleanField(label=(u'Route Setter'), required = False)
	comments = forms.CharField(label=(u'Comments'), required = False, widget=forms.Textarea)

	def check_for_errors(self, user):
		data = self.cleaned_data
		if not data["id_card"] == '':
			ids = userprofile.objects.filter(id_card = data["id_card"])
			if len(ids) == 0:
				return ''
			else:
				if ids[0].user == user:
					return ''
				else:
					return 'Error: ID number already in use.'
		return ''

	def save(self, user):
		data = self.cleaned_data
		profile = user.profile

		profile.id_card = data['id_card']
		profile.comments = data['comments']
		profile.gym_staff = data['gym_staff']

		if len(Setter.objects.filter(user=user)) == 1:
			if not data['route_setter']:
				setter = Setter.objects.get(user=user)
				setter.delete()
		else:
			if data['route_setter']:
				setter = Setter(user=user)
				setter.save()
				

		user.save()
		profile.save()

@login_required(login_url='/accounts/login/')
def staffEdit(request, user_id):
	if request.user.profile.gym_staff or request.user.is_staff:
		user = User.objects.get(pk=user_id)
		message = ''
		if request.method == 'POST':
			form = StaffForm(request.POST)
			if form.is_valid():
				message = form.check_for_errors(user)
				if len(message) == 0:
					form.save(user)
					message = 'Changes successfully saved.'
		else:
			form = StaffForm(initial = getInitialProfile(user, True))
		if not request.user.is_staff:
			form.fields['gym_staff'].widget = forms.HiddenInput()
			form.fields['route_setter'].widget = forms.HiddenInput()
		return render_to_response("userprofile/form.html", {'title': "Staff Profile Edit",  'form': form, 'message':message, 'csrf_token':csrf(request)['csrf_token']}, context_instance=RequestContext(request))
	else:
		return render_to_response("unauth.html", {})

class ProfileForm(forms.Form):
	username = forms.CharField(label=(u'Username'), required=True, max_length=30,
		widget = forms.TextInput(attrs={'readonly':'readonly'}) )
	image = forms.ImageField(label=(u'Profile Image'), required=False )
	first = forms.CharField(label=(u'First Name'), required=True, max_length=30)
	last = forms.CharField(label=(u'Last Name'), required=True, max_length=30)
	email = forms.EmailField(label=(u'Email Address'), required=True)
	birthdate = forms.DateField(('%d/%m/%Y',), label='Birth Date', required=False,
		widget=forms.DateTimeInput(format='%d/%m/%Y') )
	gender = forms.CharField(label=(u'Gender'), required=False, max_length=1,
		widget=forms.Select(choices=GENDER_CHOICES))
	#address = forms.CharField(label=(u'Mailing Address'), required=False, max_length = 100)
	phone = forms.CharField(label=(u'Phone Number'),required=False, max_length = 20 )
	website = forms.CharField(label=(u'Website'), required=False, max_length = 100)
	about = forms.CharField(label=(u'About'), required=False, widget=forms.Textarea)

	def save(self, user):
		data = self.cleaned_data

		user.first_name = data['first']
		user.last_name = data['last']
		user.email = data['email']

		profile = user.profile
		if data['image']:
			if profile.image:
				profile.image.delete()
			profile.image = data['image']
		profile.birthdate = data['birthdate']
		profile.gender = data['gender']
		#profile.address = data['address']
		profile.phone = data['phone']
		profile.website = data['website']
		profile.about = data['about']

		user.save()
		profile.save()

@login_required(login_url='/accounts/login/')
def editProfile(request):
	user = request.user
	message = ''
	if request.method == 'POST':
		form = ProfileForm(request.POST, request.FILES)
		if form.is_valid():
			form.save(user)
			return HttpResponseRedirect("/userprofile/")
	else:
		form = ProfileForm(initial = getInitialProfile(user, False))

	return render_to_response("userprofile/form.html", {'title':"Edit Profile",'form': form, 'message':message, 'csrf_token':csrf(request)['csrf_token']}, context_instance=RequestContext(request))


def renderProfile(user_id, full_profile):
	rendered = []
	user = User.objects.get(pk = user_id)
	profile = user.profile

	rendered.append(("Username", user.username))
	rendered.append(("Full name", user.first_name + " " + user.last_name))
	rendered.append(("Email", user.email))
	if full_profile:
		'''
		Removed at request of SCW
		if not profile.birthdate == None:
			rendered.append(("Birthdate", str(profile.birthdate)))
		if not profile.gender == '':
			rendered.append(("Gender", profile.gender))
		if not profile.address == '':
			rendered.append(("Address", profile.address))
		if not profile.phone == '':
			rendered.append(("Phone Number", profile.phone))
		'''
	if not profile.website == '':
		rendered.append(("Website", profile.website))
	if not profile.about == '':
		rendered.append(("About me", profile.about))

	return rendered


@login_required(login_url='/accounts/login/')
def viewProfile(request, user_id):
	thisUser = User.objects.get(pk=user_id)
	
	profile = thisUser.profile
	comparing_name = thisUser.first_name + " " + thisUser.last_name
	
	if request.user.profile.gym_staff or request.user.is_staff:
		rendered_profile = renderProfile(user_id, True)
		pass
	elif user_id == request.user.id or profile.public:
		rendered_profile = renderProfile(user_id, False)
		pass
	else:
		return render_to_response("unauth.html", {})
	
	compareMap = getHeatmap(user=thisUser)
	
	if thisUser == request.user:
		comparing_name = ""
		compareMap = ""
	
	return render_to_response("userprofile/view.html", {'profile': rendered_profile, 'thisUser':thisUser, 'image':profile.image, 'usageMap':getHeatmap(user=request.user), 'compareMap':compareMap, 'comparing_name':comparing_name}, context_instance=RequestContext(request))

@login_required(login_url='/accounts/login/')
def profile(request):
	rendered_profile = renderProfile(request.user.id, True)
	return render_to_response("userprofile/view.html", {'profile': rendered_profile, 'image':request.user.profile.image, 'usageMap':getHeatmap(user=request.user)}, context_instance=RequestContext(request))

def getInitialPrivacy(user):
    values = {}

    values['public_profile'] = user.profile.public

    usagesettings = UsageProfileSettings.objects.get_or_create(user=user)[0]
    values['public_social'] = usagesettings.public
    values['partner'] = usagesettings.partner

    return values

class PrivacyForm(forms.Form):
	public_profile = forms.BooleanField(label=(u'Make my profile public'), required=False)
	public_social = forms.BooleanField(label=(u'Allow other users to view my usage information (This will display your average gym use on your profile. Requires a public profile.)'),
					required=False)
	partner = forms.BooleanField(label=(u'Include my usage information in the workout partner search (This will allow other users to find you when searching for partners. Requires sharing usage information.)'), required=False)

	def save(self, user):
		data = self.cleaned_data

		profile = user.profile
		profile.public = data['public_profile']

		usagesettings = UsageProfileSettings.objects.get_or_create(user=user)[0]
		usagesettings.public = data['public_social']
		usagesettings.partner = data['partner']

		usagesettings.save()
		profile.save()

	def check_for_errors(self, user):
		data = self.cleaned_data
		if data['partner']:
		    if not data['public_social']:
			return 'Error: You must agree to sharing your usage information if you wish to be included in the partner search.'
		    elif not data['public_profile']:
			return 'Error: You must set your profile to public if you wish to be included in the partner search.'
		if data['public_social']:
		    if not data['public_profile']:
			return 'Error: You must set your profile to public if you wish to share your usage information with other users.'
		return ''

def privacySettings(request):
	user = request.user
	message = ''
	if request.method == 'POST':
		form = PrivacyForm(request.POST)
		if form.is_valid():
			message = form.check_for_errors(user)
			if len(message) == 0:
				form.save(user)
				message = 'Changes successfully saved.'
				return HttpResponseRedirect("/userprofile/")
	else:
		form = PrivacyForm(initial = getInitialPrivacy(user))
	return render_to_response("userprofile/form.html", {'title':"Privacy Settings",'form': form, 'message':message, 'csrf_token':csrf(request)['csrf_token']}, context_instance=RequestContext(request))

